package com.isoftstone.studentregistration.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.isoftstone.studentregistration.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api")
public class FileController {
    //读取文件上传路径
    @Value("${file.upload.path}")
    private String fileUploadPath;
    //读取文件映射路径
    @Value("${file.upload.fileMapper}")
    private String fileMapper;
    @PostMapping("/upload")
    public Result <?> uploadFile(MultipartFile file) throws IOException {
        //1.获取文件名
        String fileName = file.getOriginalFilename();
        //2.获取文件后缀
        String fileType = FileUtil.extName(fileName);
        //获取文件大小
        long fileSize = file.getSize();
        //创建文件上传目录
        File uploadParent = new File(fileUploadPath);
        if (!uploadParent.exists()) {
            uploadParent.mkdirs();
        }
        //定义唯一标识符，重新命名文件
        String uuid = IdUtil.fastSimpleUUID();
        //创建文件
        String newFileName = uuid + StrUtil.DOT + fileType;
        //文件地址
        String url = fileMapper + newFileName;
        File newFile = new File(fileUploadPath + newFileName);
        //5.将文件保存到指定目录
        file.transferTo(newFile);
        return Result.success(url);
    }
}
